<template>
  <div class="main-content" @mouseenter="stop()" @mouseleave="start()">
    <Transition v-for="(item, index) in list" :key="index">
      <div class="banner-scroll-wrap" v-show="index === selectIndex">
        {{ item.name }}
      </div>
    </Transition>
  </div>
</template>

<script setup>
const selectIndex = ref(0);
const list = ref([
  { name: "卡片1", id: 1 },
  { name: "卡片2", id: 2 },
  { name: "卡片3", id: 3 },
]);

let timer = null;

const timerFun = () => {
  timer = setInterval(() => {
    if (selectIndex.value < list.value.length - 1) {
      selectIndex.value++;
    } else {
      selectIndex.value = 0;
    }
  }, 5000);
};
timerFun();
// >开启轮播
const start = () => {
  if (timer) return;
  timeFu();
};

// >关闭轮播
const stop = () => {
  clearInterval(timer);
  timer = null;
};
onMounted(() => {
  document.addEventListener("visibilitychange", () => {
    // 用户息屏、或者切到后台运行 （离开页面）
    if (document.visibilityState === "hidden") {
      stop();
    }
    // 用户打开或回到页面
    if (document.visibilityState === "visible") {
      start();
    }
  });
});

onBeforeUnmount(() => stop());
</script>

<style lang="scss" scoped>
.main-content {
  position: relative;
  height: 100%;
  .banner-scroll-wrap {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
  }
}
.v-enter-from {
  transform: translateX(100%);
  opacity: 0;
}

.v-enter-active,
.v-leave-active {
  transition:
    transform 600ms ease-in-out,
    opacity 600ms ease-in-out;
}

.v-enter-to {
  transform: translateX(0);
  opacity: 1;
}

.v-leave-from {
  transform: translateX(0);
  opacity: 1;
}

.v-leave-to {
  transform: translateX(-100%);
  opacity: 0;
}
</style>
